from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user
from models import Post, db, Comment
from forms.community import PostForm, CommentForm

community_bp = Blueprint('community', __name__)

@community_bp.route('/')
def index():
    page = request.args.get('page', 1, type=int)
    posts = Post.query.order_by(Post.created_at.desc()).paginate(
        page=page, per_page=10, error_out=False
    )
    return render_template('community/index.html', posts=posts)

@community_bp.route('/create', methods=['GET', 'POST'])
@login_required
def create():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(
            title=form.title.data,
            content=form.content.data,
            user_id=current_user.id
        )
        db.session.add(post)
        db.session.commit()
        flash('帖子发布成功！', 'success')
        return redirect(url_for('community.detail', id=post.id))
    return render_template('community/create.html', form=form)

@community_bp.route('/<int:id>')
def detail(id):
    post = Post.query.get_or_404(id)
    post.views += 1
    db.session.commit()
    
    form = CommentForm()
    comments = Comment.query.filter_by(post_id=id).order_by(Comment.created_at.desc()).all()
    return render_template('community/detail.html', post=post, form=form, comments=comments)

@community_bp.route('/<int:id>/comment', methods=['POST'])
@login_required
def comment(id):
    post = Post.query.get_or_404(id)
    form = CommentForm()
    
    if form.validate_on_submit():
        comment = Comment(
            content=form.content.data,
            post_id=post.id,
            user_id=current_user.id
        )
        db.session.add(comment)
        db.session.commit()
        flash('评论发布成功！', 'success')
    return redirect(url_for('community.detail', id=id))

@community_bp.route('/comment/<int:id>/delete', methods=['POST'])
@login_required
def delete_comment(id):
    comment = Comment.query.get_or_404(id)
    if comment.user_id != current_user.id:
        flash('您没有权限删除此评论！', 'danger')
        return redirect(url_for('community.detail', id=comment.post_id))
        
    db.session.delete(comment)
    db.session.commit()
    flash('评论已删除！', 'success')
    return redirect(url_for('community.detail', id=comment.post_id))

@community_bp.route('/search')
def search():
    keyword = request.args.get('keyword', '')
    sort = request.args.get('sort', 'newest')
    page = request.args.get('page', 1, type=int)
    
    # 构建查询
    query = Post.query
    
    # 关键词搜索
    if keyword:
        query = query.filter(
            db.or_(
                Post.title.ilike(f'%{keyword}%'),
                Post.content.ilike(f'%{keyword}%')
            )
        )
    
    # 排序
    if sort == 'newest':
        query = query.order_by(Post.created_at.desc())
    elif sort == 'views':
        query = query.order_by(Post.views.desc())
    elif sort == 'comments':
        query = query.order_by(db.func.count(Comment.id).desc())
    
    # 分页
    posts = query.paginate(page=page, per_page=10, error_out=False)
    
    return render_template('community/search.html', 
                         posts=posts, 
                         keyword=keyword, 
                         sort=sort) 